/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.db.AnswerDAO;
import com.fire8.dolphin.db.QuestionDAO;
import com.fire8.dolphin.model.Answer;
import com.fire8.dolphin.model.Question;
import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.service.SubmitAnswer;
import com.fire8.dolphin.ui.diary.DiaryListActivity;
import com.fire8.dolphin.ui.diary.ReviewActivity;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.SmileyParser;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 回答页面
 * 
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class AnswerActivity extends Activity implements OnItemClickListener
{
    private final String TAG = "dolphin";
    
    private QuestionDAO questionDao;
    
    private AnswerDAO answerDao;
    
    private ListView listView;
    
//    private ImageButton btnText;
    
    //private ImageButton btnVoice;
    /**赞一个**/
    private Button btnSupport;
    /**评论按钮**/
    private Button btnDiscuss;
    
    private EditText txtAnswer;
    
    //private LinearLayout layoutInputContext;
    private Button btnLeft;
    //private LayoutInflater factory;
    private String locId;
    
    private String qRemoteId;
    
    private String qUserId;
    
    private SmileyParser smileyParser;
    
    private AnimationDrawable voicePlayAnim;
    
    private DolphinApplication app;
    private MyAdapter myAdapter;
    private AsynLoad anseylodar;
    private Question question;
    private ImageView imgPlayVoice;
    private ImageView currImageView;
    //private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    
    private List<Answer> list = new ArrayList<Answer>();
    
    @Override
    public void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.question_detail);
        app = (DolphinApplication)getApplication();
        registerReceiver(this.receiver, new IntentFilter(Constants.VOICE_PLAY_CALLBACK));
        smileyParser = SmileyParser.getInstance(this);
        anseylodar=new AsynLoad();//异步加载头像
        //layoutInputContext = (LinearLayout)findViewById(R.id.layout_input_context);
        btnLeft = (Button)findViewById(R.id.title_bt_left);
        //factory = LayoutInflater.from(this);
        listView = (ListView)findViewById(R.id.answer_list);
        listView.setOnItemClickListener(this);
        
        View headView = getLayoutInflater().inflate(R.layout.diary_detail_head,null);
        listView.addHeaderView(headView);
        //txtAnswer = (EditText)findViewById(R.id.txt_answer);
        btnDiscuss = (Button)findViewById(R.id.btn_discuss);
        btnSupport = (Button)findViewById(R.id.btn_support);
        //btnVoice = (ImageButton)findViewById(R.id.btn_input_voice);//语音输入
        txtAnswer = (EditText)headView.findViewById(R.id.txt_answer);
        TextView tvTitle = (TextView)headView.findViewById(R.id.tv_title);
        TextView tvContext = (TextView)headView.findViewById(R.id.tv_context);
        TextView tvAnswerNum = (TextView)headView.findViewById(R.id.tv_answer_num);
        TextView tvDate = (TextView)headView.findViewById(R.id.tv_date);
        TextView tvUserName = (TextView)headView.findViewById(R.id.tv_user_name);
        ImageView imgHead = (ImageView)headView.findViewById(R.id.img_head);
        ImageView imgContext = (ImageView)headView.findViewById(R.id.img_context);
        imgPlayVoice = (ImageView)headView.findViewById(R.id.img_play_voice);
        TextView tvTimeLong = (TextView)headView.findViewById(R.id.tv_time_long);
        Intent intent = getIntent();
        String from = intent.getStringExtra("from");
        if("self".equals(from))
        {
            locId = intent.getStringExtra("locId");
            Log.i(TAG,"接收的locId: "+locId);
            question = new QuestionDAO(this).getObject(locId);
            
        }else
        {
            question = (Question)intent.getSerializableExtra("question");
        }
        if (question != null)
        {
            qRemoteId = question.getRemoteId();
            qUserId = question.getUserId();
            tvTitle.setText(question.getTitle());
            tvContext.setText(question.getContext());
            tvAnswerNum.setText("回复:"+question.getAnswerNum());
            tvDate.setText(question.getUpdateDate());
            anseylodar.showimgAnsy(imgHead,RequestUtils.IMG_URL+qUserId+".jpg");//异步加载图片
            if(!StringUtil.isEmpty(question.getPicture()))
            {
                imgContext.setVisibility(View.VISIBLE);
                if(question.getPicture().contains("http"))
                {
                    //显示网络图片
                    anseylodar.showimgAnsy(imgContext,question.getPicture());//异步加载图片
                }else
                {
                    //如果是本地的，则显示本地图片
                    Options opt = new BitmapFactory.Options();
                    opt.inSampleSize = 4;
                    Bitmap bmp = BitmapFactory.decodeFile(question.getPicture(),opt);
                    imgContext.setImageBitmap(bmp);
                }
            }
            
            tvUserName.setText(question.getUserName() == null ? "未知" : question.getUserName());
            if(!StringUtil.isEmpty(question.getVoice()))
            {
                tvTimeLong.setText(question.getVoiceLong()+"\"");
                imgPlayVoice.setBackgroundResource(R.anim.voice_play_gray);
                imgPlayVoice.setTag(question.getVoice());
                imgPlayVoice.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //播放录音
                        imgPlayVoice.setImageDrawable(null);
                        voicePlayAnim = (AnimationDrawable)v.getBackground();
                        voicePlayAnim.start();
                        sendMessage(Constants.MEDIA_INIT,(String)v.getTag());
                        currImageView = imgPlayVoice;
                    }
                });
            }
        }
        if(!app.getUserId().equals(qUserId))
        {
            //如果这个问题不是自己提的，并且自己不是客服，则隐藏回答按钮
            if(UserInfo.USER_TYPE_CLIENT.equals(Integer.valueOf(app.getUserType())))
            {
                //findViewById(R.id.layout_bottom_button).setVisibility(View.GONE);
            }
        }
        answerDao = new AnswerDAO(this);
        setElement();
        myAdapter = new MyAdapter(this);
        listView.setAdapter(myAdapter);
        new RequestAnswerTask().execute(qRemoteId);
    }
    
    @Override
    protected void onStart()
    {
        super.onStart();
        findAnswerList();
    }
    
    /**
     * <一句话功能简介>
     * <功能详细描述> [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void findAnswerList()
    {
        if (!StringUtil.isEmpty(locId))
        {
            Log.i(TAG, "查询时 locId: " + locId);
            Answer answer = new Answer();
            answer.setqId(locId);
            list = answerDao.findList(answer);
            myAdapter.notifyDataSetChanged();
            Log.i(TAG, "记录数: " + list.size());
        }
    }
    
    private void setElement()
    {

        
        btnDiscuss.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //评论按钮
                //检查是否有注册或登录，如果没有，则不能提交
                if(StringUtil.isEmpty(app.getAccount()))
                {
                    Toast.makeText(AnswerActivity.this, "请注册或登录后才能使用", Toast.LENGTH_LONG).show();
                    return;
                }
                Intent intent = new Intent(AnswerActivity.this,ReviewActivity.class);
                intent.putExtra("qRemoteId", qRemoteId);
                intent.putExtra("qUserId", qUserId);
                startActivityForResult(intent, ReviewActivity.class.hashCode());
            }
        });
        btnSupport.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
              //检查是否有注册或登录，如果没有，则不能提交
                if(StringUtil.isEmpty(app.getAccount()))
                {
                    Toast.makeText(AnswerActivity.this, "请注册或登录后才能使用", Toast.LENGTH_LONG).show();
                    return;
                }
                //赞一个按钮
                new SupportTask().execute("");
            }
        });
        btnLeft.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //返回按钮，将聊天窗口关闭
                AnswerActivity.this.finish();
            }
        });
        
    }
    
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;
        
        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }
        
        public int getCount()
        {
            return list.size();
        }
        
        public Object getItem(int position)
        {
            return null;
        }
        
        public long getItemId(int position)
        {
            return 0;
        }
        
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder = null;
            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.answer_item, null);
                holder.tvAnswer = (TextView)convertView.findViewById(R.id.tv_answer);
                holder.tvAnswerName = (TextView)convertView.findViewById(R.id.tv_user_name);
                holder.tvDate = (TextView)convertView.findViewById(R.id.tv_date);
                holder.imgHead = (ImageView)convertView.findViewById(R.id.img_head);
                holder.imgAnswer = (ImageView)convertView.findViewById(R.id.img_answer);
                holder.tvVoiceLong = (TextView)convertView.findViewById(R.id.tv_time_long);
                convertView.setTag(holder);
                
            }
            else
            {
                holder = (ViewHolder)convertView.getTag();
            }
            Answer ans = list.get(position);
            
            
            
            if (!StringUtil.isEmpty(ans.getVoice()))
            {
                holder.imgAnswer.setBackgroundResource(R.anim.voice_play_gray);
                //holder.imgAnswer.setImageResource(R.drawable.ptt_action_l_3);
                holder.imgAnswer.setTag(ans.getVoice());
                holder.imgAnswer.setVisibility(View.VISIBLE);
                holder.tvVoiceLong.setText(ans.getVoiceLong()+"\"");
            }
            String strAnswer = ans.getaContext();
            if(!StringUtil.isEmpty(strAnswer))
            {
                Spannable spans = smileyParser.addSmileySpans(strAnswer);//将文字转换为图形
                holder.tvAnswer.setText(spans);
                holder.tvAnswer.setVisibility(View.VISIBLE);
            }
            
            String userName = ans.getUserName();
            holder.tvAnswerName.setText(userName == null ? "未知" : userName);
            
            holder.tvDate.setText(ans.getUpdateDate());
            final String userId = ans.getUserId();
            holder.imgHead.setTag(RequestUtils.IMG_URL+userId+".jpg");
            anseylodar.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+userId+".jpg");//异步加载图片
            holder.imgHead.setOnClickListener(new OnClickListener()
            {
                
                @Override
                public void onClick(View v)
                {
                    if(!RequestUtils.getInstall().isConnect(AnswerActivity.this))
                    {
                        Toast.makeText(AnswerActivity.this, "网络无法连接，请稍候再试", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Intent intent = new Intent(AnswerActivity.this,
                            UserInfoActivity.class);
                    intent.putExtra("from", "answer");
                    intent.putExtra("userId", userId);
                    startActivity(intent);
                }
            });
            return convertView;
        }
        public final class ViewHolder
        {
            public ImageView imgAnswer;
            public ImageView imgHead;
            public TextView tvAnswer;
            public TextView tvAnswerName;
            public TextView tvDate;
            public TextView tvVoiceLong;//语音长度
            
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id)
    {
        LogUtil.d("position:"+position);
        if(position ==0)return;
        currImageView = (ImageView)view.findViewById(R.id.img_answer);
        if (currImageView.getTag() != null)
        {
            currImageView.setImageDrawable(null);
            voicePlayAnim = (AnimationDrawable)currImageView.getBackground();
            voicePlayAnim.start();
            String url = (String)currImageView.getTag();
            Log.i(TAG, "点击了语音,地址： " + url);
            //启动任务，播放语音、显示动画
            sendMessage(Constants.MEDIA_INIT,url);
        }
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        new RequestAnswerTask().execute(qRemoteId);
    }

    
    /**发送控制指令播或停止语音**/
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.VOICE_PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    /**定义广播接收器**/
    private BroadcastReceiver receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            int commend = intent.getIntExtra("command", 0);
            switch (commend)
            {
                case Constants.MEDIA_INIT:
                    //初始化完成,已经开始播放，修改播放状态
                    
                    break;
                case Constants.MEDIA_START:
                    //启动动画
                    if(!voicePlayAnim.isRunning())
                    {
                        
                        voicePlayAnim.start();
                    }
                    break;
                case Constants.MEDIA_PAUSE:
                    
                    if (voicePlayAnim != null)
                    {
                        currImageView.setImageResource(R.drawable.play3_gray);
                        voicePlayAnim.stop();
                    }
                    break;
                case Constants.MEDIA_STATUS_STOP:
                    //播放完成，修改播放状态
                    if (voicePlayAnim != null)
                    {
                        currImageView.setImageResource(R.drawable.play3_gray);
                        voicePlayAnim.stop();
                    }
                    break;
                default:
                    break;
            }
        }
        
    };
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    
    //异步任务 获取问题的答案
    class RequestAnswerTask extends AsyncTask<String, Void, String> 
    {

        @Override
        protected String doInBackground(String... params)
        {
            if(!RequestUtils.getInstall().isConnect(AnswerActivity.this))
            {
                return "网络不可用";
            }
            //LogUtil.d("异步任务 获取问题的答案，问题ID："+params[0]);
            List<Answer> answers = RequestUtils.getInstall().getAnswer(params[0]);
            if(qUserId.equals(app.getUserId()))
            {
                for (Answer ans : answers)
                {
                    ans.setqId(locId);
                    answerDao.add(ans);
                }
            }
            list.clear();
            list.addAll(answers);
            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            myAdapter.notifyDataSetChanged();
        }
        
    }
    /**赞一个按钮**/
    class SupportTask extends AsyncTask<String, Void, String> 
    {
        @Override
        protected String doInBackground(String... arg0)
        {
            if(!RequestUtils.getInstall().isConnect(AnswerActivity.this))
            {
                return null;
            }
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("questionId",qRemoteId));
            param.add(new BasicNameValuePair("userId",qUserId));
            String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"/question/support.php", param);
            if(!StringUtil.isEmpty(json))
            {
                return "谢谢您的鼓励";
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(!StringUtil.isEmpty(result))
            {
                Toast.makeText(AnswerActivity.this, result, Toast.LENGTH_LONG).show();
                //重新加载页面数据
            }
        }
    }
}
